package com.deepexp.equip;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.deepexp.equip.entity.Auth;
import com.deepexp.equip.entity.EquipEntity;
import com.deepexp.equip.entity.EquipResponse;
import com.deepexp.equip.entity.Result;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MainActivity extends AppCompatActivity {
    private TextView tv_AddMore;
    private TextView tv_Level;
    private TextView tv_authBalance;
    private TextView tv_Recharge;
    private ProgressBar pb_Load;
    private EquipEntity equipEntity;
    private Auth auth;
    private LinearLayout ll_Toast;
    private TimerTask timerTask;
    private Timer timer;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
//                    addView();
                    break;
                case 2:
                    ll_Toast.removeViewAt(0);
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String postData = "";
        tv_AddMore = findViewById(R.id.tv_AddMore);
        tv_Level = findViewById(R.id.tv_Level);
        ll_Toast = findViewById(R.id.ll_Toast);
        tv_authBalance = findViewById(R.id.tv_authBalance);
        tv_Recharge = findViewById(R.id.tv_Recharge);
        pb_Load = findViewById(R.id.pb_Load);
        getEquipInfo();
        getAuthInfo();
        setListener();
        initTimer();
//        addView();
    }

    public void AddMoney() {
        Call<JsonObject> call = (Call) RetrofitUtil.getInstance(MainActivity.this).getService().addMoney();
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                JsonObject jsonObject = response.body();
                try {
                    Result result = new Gson().fromJson(jsonObject.toString(), Result.class);
                    if (result.getCode().equals("0")) {
//                        tv_authBalance.setText("剩余:" + auth.getAuth_balance() + "元宝");
                        getAuthInfo();
                        Toast.makeText(MainActivity.this, "充值成功!", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(MainActivity.this, "充值失败!", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Log.i("报错", "" + e.getMessage());
                }

            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Log.i("失败", "" + t.getMessage());
            }
        });
    }

    private void getAuthInfo() {
        Call<JsonObject> call = (Call) RetrofitUtil.getInstance(MainActivity.this).getService().getAuth();
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                JsonObject jsonObject = response.body();
                try {
                    auth = new Gson().fromJson(jsonObject.toString(), Auth.class);
                    tv_authBalance.setText("剩余:" + auth.getAuth_balance() + "元宝");
                } catch (Exception e) {
                    Log.i("报错", "" + e.getMessage());
                }

            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Log.i("失败", "" + t.getMessage());
            }
        });
    }


    public void getEquipInfo() {

        Call<JsonArray> call = (Call) RetrofitUtil.getInstance(MainActivity.this).getService().getPin();
        call.enqueue(new Callback<JsonArray>() {
            @Override
            public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
//                EquipResponse EquipResponse = response.body();
                try {
                    List<EquipEntity> dataArr = com.alibaba.fastjson.JSONArray.parseArray(response.body().toString(), EquipEntity.class);
                    Log.i("成功", "" + response.body());
                    if (dataArr.size() > 0) {
                        equipEntity = dataArr.get(0);
                        tv_Level.setText("+" + equipEntity.getEquip_level());
                    }
                } catch (Exception e) {
                    Log.i("报错", "" + e.getMessage());
                }

            }

            @Override
            public void onFailure(Call<JsonArray> call, Throwable t) {
                Log.i("失败", "" + t.getMessage());
            }
        });
    }

    public void AddEquip() {
        pb_Load.setVisibility(View.VISIBLE);
        tv_AddMore.setVisibility(View.GONE);
        Call<JsonObject> call = (Call) RetrofitUtil.getInstance(MainActivity.this).getService().AddMore();
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                pb_Load.setVisibility(View.GONE);
                tv_AddMore.setVisibility(View.VISIBLE);
                Log.i("成功", "" + response.message());
                if (timer == null || timerTask == null) {
                    initTimer();
                }
                JsonObject jsonObject = response.body();
                if (jsonObject != null) {
                    Result result = new Gson().fromJson(jsonObject.toString(), Result.class);
//                    Toast toast = null;
                    String toast = "";
                    if (result.getCode().equals("0")) {
                        toast = "恭喜你，增幅成功！";
                        tv_Level.setText("+" + (equipEntity.getEquip_level() + 1));
                        equipEntity.setEquip_level(equipEntity.getEquip_level() + 1);
                    }else if (result.getCode().equals("-900")){
//                        Toast.makeText(MainActivity.this, "!", Toast.LENGTH_SHORT).show();
                        toast = "请求失败！";
                    }  else {
                        toast = "很遗憾，增幅失败~";
                        tv_Level.setText("+" + (equipEntity.getEquip_level() - 1));
                        equipEntity.setEquip_level(equipEntity.getEquip_level() - 1);
                    }
                    getAuthInfo();
                    addView(toast);
//                    getEquipInfo();
//                    toast.setGravity(Gravity.TOP, 0, 20);
//                    toast.show();
                }


            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Log.i("失败", "" + t.getMessage());
                pb_Load.setVisibility(View.GONE);
                tv_AddMore.setVisibility(View.VISIBLE);
            }
        });
    }


    public void initTimer() {
        if (timer == null) {
            timer = new Timer();
        }
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    if (ll_Toast.getChildCount() > 0) {
                        int size = ll_Toast.getChildCount();
                        long time = (long) ll_Toast.getChildAt(0).getTag();
                        if (((new Date().getTime() - time)) > 2500) {
                            handler.sendEmptyMessage(2);
                        }
                    } else {
                        cancelTimer();
                    }
                }
            };
        }

        timer.schedule(timerTask, 0, 1000);
    }

    private void setListener() {
        tv_AddMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (equipEntity.getEquip_level() >= 15) {
                    Toast toast = Toast.makeText(MainActivity.this, "已强化至最高级别无法在进行强化!", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP, 0, 20);
                    toast.show();
                } else if (auth.getAuth_balance() < 10) {
                    Toast toast = Toast.makeText(MainActivity.this, "余额不足,请充值后在强化!", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP, 0, 20);
                    toast.show();
                } else {
                    AddEquip();
                }
            }
        });

        tv_Recharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddMoney();
            }
        });
    }

    public void addView(String toast) {
        TextView textView = new TextView(MainActivity.this);
        LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        textView.setLayoutParams(lparams);
        textView.setText(toast);
        textView.setGravity(Gravity.CENTER);
        textView.setTag(new Date().getTime());
        textView.setTextColor(Color.WHITE);
        if (ll_Toast.getChildCount() >= 3) {
            ll_Toast.removeViewAt(0);
        }
        ll_Toast.addView(textView);
//        handler.sendEmptyMessageDelayed(1, 1500);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelTimer();
    }

    public void cancelTimer() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

}
